<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Random" %><%--
  Created by IntelliJ IDEA.
  User: lzy
  Date: 18-8-2
  Time: 上午11:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>book detail</title>
</head>
<body>

<h4 style="color: blueviolet">Book Details</h4>

<%
    String book = request.getParameter("book");
    // 把书的信息以Cookie方式传回给浏览器，删除一个Cookie
    // 1.确定要被删除的Cookie，
    // 前提：以lastbrowse开头的cookie数量大于等于5
    // a.若从books.jsp页面传入的book不在以lastbrowse开头的Cookie,则删除较早的那个
    // b.否则删除第一个Cookie即可
    Cookie[] cookies = request.getCookies();
    List<Cookie> bookCookies = new ArrayList<>();
    Cookie cookieForDelete = null;
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().startsWith("lastbrowse_")) {
                bookCookies.add(cookie);
                if (book.equals(cookie.getValue())) {
                    cookieForDelete = cookie;
                }
            }
        }
    }

    if (bookCookies.size() >= 5) {
        if (cookieForDelete == null) {
            cookieForDelete = bookCookies.get(0);
        }
    }

    if (cookieForDelete != null) {
        // 删除cookie
        cookieForDelete.setMaxAge(0);
        response.addCookie(cookieForDelete);
    }

    // 2.把从books.jsp传入的book作为一个Cookie值返回
    Cookie cookie = new Cookie(("lastbrowse_" + new Random().nextInt(1000)), request.getParameter("book"));
    response.addCookie(cookie);
%>
Book:<%=request.getParameter("book")%>

<br/><br/>

<a href="books.jsp">Return</a>

</body>
</html>
